package People;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import java.sql.*;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class MainViewer {

    private JButton filterAnagrafica;
    private JButton newAnagrafica;
    private JFrame frame;
    private JTable table;
    
    public MainViewer() {    	
		Toolkit tk = Toolkit.getDefaultToolkit();
    		Dimension screenSize = tk.getScreenSize();
    		Utilities.initDB();
    		
        frame = new JFrame("People");
        frame.setSize(800, 600);
        frame.setLocation(screenSize.width / 2 - frame.getSize().width / 2, screenSize.height / 2 - frame.getSize().height / 2);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel container = new JPanel();
        container.setLayout(new BorderLayout());
        container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        frame.getContentPane().add(container);

        // setting up the title
        JLabel title = new JLabel("Elenco Anagrafiche");
        title.setFont(Utilities.getGeorgia36());
        JPanel panel = new JPanel();
        panel.add(title, BorderLayout.CENTER);
        container.add(panel, BorderLayout.NORTH);        
        
        // setting up buttons
        filterAnagrafica = new JButton("Filtra");
        filterAnagrafica.setFont(Utilities.getGeorgia24());
        filterAnagrafica.addActionListener(filterHandler);
        newAnagrafica = new JButton("Nuova");
        newAnagrafica.setFont(Utilities.getGeorgia24());
        newAnagrafica.addActionListener(newHandler);

        JPanel buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
        buttons.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        buttons.add(filterAnagrafica);
        buttons.add(Box.createHorizontalGlue());
        buttons.add(newAnagrafica);
        container.add(buttons, BorderLayout.SOUTH);
        
	    	table = new JTable();
	    	table.setFont(Utilities.getGeorgia20());
	    	table.setRowHeight(Utilities.getGeorgia20().getSize() + 5);
	    	table.getTableHeader().setFont(Utilities.getGeorgia20());
	    	table.setDefaultRenderer(Object.class, new AlternateRowsColor());
	    	table.addMouseListener(new MouseAdapter(){
	    		public void mouseClicked(MouseEvent e){
	    			if (e.getClickCount() == 2) {
	            		frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	    				int id = Integer.parseInt(table.getModel().getValueAt(table.getSelectedRow(), 0).toString());
	    				openAnagraficaViewer(id);
	            		frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	    			}
	    		}
	    		});
	    	
	    viewAnagrafiche();
	    	
        container.add(new JScrollPane(table), BorderLayout.CENTER);        

        frame.setVisible(true);
    }

    private void openAnagraficaViewer(int id) {
		new AnagraficaViewer(id);
		frame.dispose();
    }
    
    public void viewAnagrafiche() {
    		viewAnagrafiche(getAnagrafiche());
    }
    
    public void viewAnagrafiche(Vector<Anagrafica> anagrafiche) {
		table.setModel(new AnagraficaTableModel(anagrafiche));
	    	table.getColumnModel().getColumn(0).setMinWidth(50);
	    	table.getColumnModel().getColumn(0).setMaxWidth(50);
    }

    private Vector<Anagrafica> getAnagrafiche() {
		Vector<Anagrafica> v = new Vector<Anagrafica>();
		
		try {
			Connection c = Utilities.connection;
			Statement s = c.createStatement();
			ResultSet r = s.executeQuery("SELECT * FROM person");

			while (r.next())
	    			v.add(new Anagrafica(r.getInt(1)));
			
		    r.close();
			s.close();
				    
		} catch (SQLException e) {
			System.out.println(e.toString());
		}
		
		return v;
    }
    
    ActionListener filterHandler = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        		frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			new AnagraficaFilter();
			frame.dispose();
			frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    };

    ActionListener newHandler = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
			openAnagraficaViewer(0);
        }
    };
    
    public class AnagraficaTableModel extends AbstractTableModel {
    		private Vector<Anagrafica> anagrafiche;
		private String[] colName = {"Id", "Cognome", "Nome", "Stato"};
    	
	    	AnagraficaTableModel() {}
	
	    	AnagraficaTableModel(Vector<Anagrafica> anagrafiche) {
	    		this.anagrafiche = anagrafiche;
	    	}
	    	
	    	public void setAnagrafiche(Vector<Anagrafica> anagrafiche) {
	    		this.anagrafiche = anagrafiche;
	    	}
	    	
	    	public int getColumnCount() {
	    		return colName.length;
	    	} 
	
	    	public int getRowCount() {
	    		return anagrafiche == null ? 0 : anagrafiche.size();
	    	}
	    	
	    	public Object getValueAt(int row, int col) {
	    		Anagrafica a = (Anagrafica)anagrafiche.elementAt(row);

	    		switch (col){
	    			case 0:
	    				return a.getId();
	    			case 1:
	    				return a.getSurname();
	    			case 2:
	    				return a.getName();
	    			case 3:
	    				String st = "";
	    		        try {
	    					Connection conn = Utilities.connection;
	    					Statement s = conn.createStatement();
	    					ResultSet r = s.executeQuery("SELECT description FROM state WHERE id = " + a.getState());
	    					if (r.next())
	    						st = r.getString(1);
	    				    r.close();				
	    					s.close();
	    				} catch(Exception e) {  
	    		            System.out.println("Error : " + e.toString());  
	    				}

	    				return st;
	    			default:
	    				return "errore";
	    		 }
	    	} 
	
	    	public String getColumnName(int col) {
	    		return colName[col]; 
	    	} 
	    	
	    	public boolean isCellEditable(int row, int col) { 
	    		return false; 
	    	} 
    }

    public class AlternateRowsColor extends DefaultTableCellRenderer {

        private Color currentColor = Color.white;

        public AlternateRowsColor() {
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int col) {
            if (row % 2 == 0) {
                currentColor = Color.white;
            } else {
                currentColor = new Color(220, 255, 255);
            }

            if (selected) {
                super.setForeground(table.getSelectionForeground());
                super.setBackground(table.getSelectionBackground());
            } else {
                super.setForeground(Color.black);
                super.setBackground(currentColor);
            }
            setFont(table.getFont());
            setValue(value);
            return this;
        }
    }
}
